<?php

namespace App\Api\Controllers\Vbill;


use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class BaseController
{
    public $scan_url = "https://openapi.tianquetech.com/order/reverseScan"; //被扫接口（B扫C）
    public $order_query_url = "https://openapi.tianquetech.com/query/tradeQuery";
    public $refund_url = 'https://openapi.tianquetech.com/order/refund';
    public $refund_query_url = 'https://openapi.tianquetech.com/query/refundQuery';
    public $qr_pay_url = 'https://openapi.tianquetech.com/order/jsapiScan';

    public $upload_url = "https://openapi.suixingpay.com/merchant/uploadPicture"; //图片上传
    public $open_store_url = 'https://openapi.suixingpay.com/merchant/income'; //进件接口
    public $open_update_store_url = 'https://openapi.suixingpay.com/merchant/updateMerchantInfo'; //进件失败修改接口
    public $open_query_store_url = 'https://openapi.suixingpay.com/merchant/queryMerchantInfo'; //入驻查询
    public $weixin_config = "https://openapi.suixingpay.com/merchant/weChatPaySet/addConf"; //微信子商户号配置
    public $store_query_info = "https://openapi.suixingpay.com/merchant/merchantInfoQuery"; //商户信息查询接口
    public $update_rate = "https://openapi.suixingpay.com/merchant/merchantSetup"; //修改费率信息接口
    public $wechat_commit_apply = "https://openapi.suixingpay.com/merchant/realName/commitApply"; //提交实名认证申请接口
    public $queryApplyInfo = "https://openapi.suixingpay.com/merchant/realName/queryApplyInfo"; // 实名认证申请结果查询
    public $backApplyBill = "https://openapi.suixingpay.com/merchant/realName/backApplyBill"; // 实名认证申请撤销
    public $wechat_lose_face = "https://openapi.tianquetech.com/query/wechatLoseFace"; //获取微信刷脸调用凭证
    public $getUnionInfo = "https://openapi.tianquetech.com/query/getUnionInfo"; //银联获取信息

    public $alipay_commit_apply = "https://openapi.suixingpay.com/merchant/alipayRealName/commitApply";
    public $alipayQueryApplyInfo = "https://openapi.suixingpay.com/merchant/alipayRealName/queryApplyInfo"; // 实名认证申请结果查询
    public $alipayBackApplyBill = "https://openapi.suixingpay.com/merchant/alipayRealName/backApplyBill"; // 实名认证申请撤销

    public function execute($data, $url, $privateKey, $sxfpublic)
    {
        $mygoods = $this->argSort($data);
        $mystr = $this->createLinkstring($mygoods);
        $sxfpublic = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($sxfpublic, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";

        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($privateKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";

        $sign = $this->rsaSign($mystr, $privateKey);
        $mygoods['sign'] = $sign;
        $datajsonstr = json_encode($mygoods, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $curl = curl_init();
        $this_header = array("content-type: application/x-www-form-urlencoded; charset=UTF-8");
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this_header);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $datajsonstr);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($datajsonstr)
        ));
        //  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //file_put_contents('b423423525.log',var_export($datajsonstr,true)."\r\n",FILE_APPEND);
        //        file_put_contents('b423423525.log',var_export($tmpInfo,true)."\r\n",FILE_APPEND);
        $info = json_decode($tmpInfo, JSON_UNESCAPED_UNICODE);
//        Log::info('随行付执行结果返回');
//        Log::info($info);

        return [
            'status' => 1,
            'data' => $info
        ];

        $newsign = $info['sign'];
        unset($info['sign']);
        ksort($info);
        $mystrs2 = $this->createLinkstring($info);

        if ($this->verify($mystrs2, $newsign, $sxfpublic)) {
            return [
                'status' => 1,
                'data' => $info
            ];

        } else {

            return [
                'status' => 0,
                'message' => '平台请求返回异常',
                'data' => $info
            ];
        }


    }

    /**
     * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param $para 需要拼接的数组
     * return 拼接完成以后的字符串
     */
    function createLinkstring($para)
    {
        $params = array();
        foreach ($para as $key => $value) {
            if (is_array($value)) {
                if (isset($value['couponDetail']) && !empty($value['couponDetail'])) {
                    $value['couponDetail'] = addslashes($value['couponDetail']);
                }
                $value = stripslashes(json_encode($value, JSON_UNESCAPED_UNICODE));
            }
            $params[] = $key . '=' . $value;
        }
        $data = implode("&", $params);

        return $data;
    }

    //增加退款订单
    function add_refund_orders($refund_no, $out_trade_no, $refund_amount)
    {
        $order = DB::table('orders')->where('out_trade_no', $out_trade_no)->select('store_id', 'created_at')->first();
        $data = array('refund_no' => $refund_no, 'refund_amount' => $refund_amount, 'out_trade_no' => $out_trade_no, 'store_id' => $order->store_id, 'refund_time' => date('Y-m-d H:i:s', time()), 'created_at' => $order->created_at);

        $refund_order = DB::table('all_refund_orders')->where('out_trade_no', $out_trade_no)->select('store_id', 'created_at')->first();
        if (empty($refund_order)) {
            DB::table('all_refund_orders')->insert($data);
        }
    }

    /**
     * 对数组排序
     * @param $para 排序前的数组
     * return 排序后的数组
     */
    function argSort($para)
    {
        ksort($para);
        // reset($para);
        return $para;
    }

    /**
     * RSA签名
     * @param $data 待签名数据
     * @param $private_key_path 商户私钥文件路径
     * return 签名结果
     */
    function rsaSign($data, $private_key_path)
    {
        //$priKey = file_get_contents($private_key_path);
        //$priKey=chunk_split($priKey, 64, "\n");
        $res = openssl_get_privatekey($private_key_path);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        //base64编码
        $sign = base64_encode($sign);
        return $sign;
    }


    /**RSA验签
     * $data待签名数据
     * $sign需要验签的签名
     * 验签用支付宝公钥
     * return 验签是否通过 bool值
     */
    function verify($data, $sign, $pubKey)
    {
        // $pubKey = file_get_contents('key/alipay_public_key.pem');
        //转换为openssl格式密钥
        $res = openssl_get_publickey($pubKey);
        //调用openssl内置方法验签，返回bool值
        $result = (bool)openssl_verify($data, base64_decode($sign), $res);
        //var_dump($result);
        //释放资源
        openssl_free_key($res);
        //返回资源是否成功
        return $result;
    }


}